import { Component, OnDestroy, OnInit } from '@angular/core';
import { ViewerItem, ViewerLayoutService } from '@services/viewer-layout.service';
import { Subscription } from 'rxjs';
import { MatDialog } from '@angular/material/dialog';
import { ProcessTypeSelectComponent } from './process-type-select/process-type-select.component';


@Component({
  selector: 'zlyt-space',
  templateUrl: './space.component.html',
  styleUrls: ['./space.component.scss']
})
export class SpaceComponent implements OnInit, OnDestroy {

  public viewers: ViewerItem[] = [];
  private viewerSubscription: Subscription | null = null;

  constructor(
    private viewerLayout: ViewerLayoutService,
    private dialog: MatDialog
  ) {
  }

  ngOnInit(): void {
    this.viewersMonitor();
  }

  ngOnDestroy(): void {
    this.viewerSubscription?.unsubscribe();
  }

  async handleImageChange(image: File): Promise<void> {
    this.viewerLayout.setSource(image);
  }

  private viewersMonitor(): void {
    this.viewerSubscription = this.viewerLayout.viewer$.subscribe(res => {
      this.viewers = res;
    });
  }

  handleAaddNewProcess(): void {
    const dialogRef = this.dialog.open(ProcessTypeSelectComponent, {
      width: '60vw',
      ariaLabel: 'process type select dialog.'
    });
    dialogRef.afterClosed().subscribe(res => {
      if (res && this.viewerLayout.existSource()) {
        this.viewerLayout.addViewer(res)
      }
    })
  }

}
